<?php
namespace app\controllers;

use yii\web\Controller;
use yii\di\Container;
use yii\di\ServiceLocator;

/**
 * Class DependencyInjectController
 * 依赖注入
 * @package app\controllers
 * @author  diligentyang
 */
Class DependencyInjectController extends Controller
{
    public function actionIndex()
    {
//        $container = new Container();
//        //指定接口和类的对应关系
//        $container->set('app\controllers\Driver', 'app\controllers\ManDriver');
//        //$driver = new ManDriver
//        //$car = new Car($driver);
//        //实例化
//        $car = $container->get('app\controllers\Car');
//        $car->run();

        //使用全局容器指定对应关系
//        \Yii::$container->set('app\controllers\Driver', 'app\controllers\ManDriver');
//
//        $sl = new ServiceLocator();
//        $sl->set('car', [
//            'class'=>'app\controllers\Car'
//        ]);
//        $car=$sl->get('car');
//        $car->run();


        //在config/web.php 的 components 中添加
        /*
         'car' => [
            'class'=>'app\controllers\Car'
        ]
         */
        \Yii::$container->set('app\controllers\Driver', 'app\controllers\ManDriver');
        //app就是个服务定位器
        \Yii::$app->car->run();


    }
}

interface Driver
{
    public function drive();
}

class ManDriver implements Driver
{
    public function drive()
    {
        echo "i am an old man!";
    }
}

class Car
{

    private $driver = null;
    //构造函数中，传入
    public function __construct(Driver $driver)
    {
        $this->driver = $driver;
    }

    public function run()
    {
        $this->driver->drive();
    }
}